package icu.yougan.trade.service.Impl;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

// 新增EmailCodeService.java
@Service
@RequiredArgsConstructor
@Log4j2
public class EmailCodeServiceImpl {
    private final JavaMailSender mailSender;
    private final StringRedisTemplate redisTemplate;

    public void sendCode(String email, CodeType type) {
        // 生成6位随机验证码
        String code = RandomStringUtils.randomNumeric(6);

        // 存储到Redis
        String key = "code:" + type.name() + ":" + email;
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

        //构建邮件内容
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 设置邮件基本信息
            helper.setFrom("843972445@qq.com"); // 与配置的username一致
            helper.setTo(email);
            helper.setSubject(type.getDesc() + "验证码");

            // HTML内容模板
            String content = String.format("""
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                <h2 style="color: #1890ff;">校园二手交易平台</h2>
                <p>尊敬的会员：</p>
                <p>您的<strong>%s</strong>验证码是：</p>
                <div style="font-size: 24px; letter-spacing: 3px; color: #ff4d4f; margin: 15px 0;">
                    %s
                </div>
                <p>有效期5分钟，请勿泄露给他人</p>
                <hr style="border-color: #f0f0f0;">
                <p style="color: #999; font-size: 12px;">
                    若非本人操作，请忽略本邮件
                </p>
            </div>
            """, type.getDesc(), code);

            helper.setText(content, true); // true表示HTML内容

            // 发送邮件
            CompletableFuture.runAsync(() -> {
                try {
                    mailSender.send(message);
                    log.info("验证码邮件发送成功，邮箱：{}，类型：{}", email, type);
                } catch (MailException e) {
                    log.error("邮件发送失败，邮箱：{}，错误：{}", email, e.getMessage());
                    // 可选：从Redis删除已存储的验证码
                    redisTemplate.delete(key);
                }
            });

        } catch (MessagingException e) {
            log.error("构建邮件失败：{}", e.getMessage());
            throw new RuntimeException("邮件发送服务异常", e);
        }
    }

    public boolean verifyCode(String email, String code, CodeType type) {
        String key = "code:" + type.name() + ":" + email;
        System.out.println(redisTemplate.opsForValue().get(key));
        return code.equals(redisTemplate.opsForValue().get(key));
    }

    public enum CodeType {
        REGISTER("账号注册"),
        RESET_PWD("密码重置");

        private final String desc;

        CodeType(String desc) {
            this.desc = desc;
        }

        public String getDesc() {
            return desc;
        }
    }
}